package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.projectcore.enumeration.MenuAffiliationEnum;
import com.eastfair.venueservice.dao.ViolationProjectMapper;
import com.eastfair.venueservice.dto.ViolationProjectDTO;
import com.eastfair.venueservice.entity.ViolationProject;
import com.eastfair.venueservice.service.VenueManageUserAccountService;
import com.eastfair.venueservice.service.ViolationProjectService;
import com.eastfair.venueservice.vo.ViolationProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 违规项目
 * </p>
 *
 * @author dqq
 * @date 2023-03-15
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ViolationProjectServiceImpl extends SuperServiceImpl<ViolationProjectMapper, ViolationProject> implements ViolationProjectService {

    @Resource
    private VenueManageUserAccountService venueManageUserAccountService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ViolationProject> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ViolationProject model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return super.handlerSave(model);
    }

    @Override
    public Page<ViolationProjectVO> listViolationProjectVO(PageParams<ViolationProjectDTO> pageParams, Function<ViolationProjectDTO, QueryWrapper<ViolationProject>> queryWrapperFunction) {
        log.info("listViolationProjectVO - 查询违规项目列表, pageParams={}", pageParams);
        QueryWrapper<ViolationProject> queryWrapper = queryWrapperFunction.apply(pageParams.getModel());
        Page<ViolationProject> page = page(pageParams.buildPage(), queryWrapper);
        Page<ViolationProjectVO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        List<ViolationProject> list = page.getRecords();
        if (list == null || list.isEmpty()) {
            return voPage;
        }
        // 用户ID列表查询创建人
        List<Long> createBys = list
                .stream()
                .map(SuperEntity::getCreatedBy)
                .collect(Collectors.toList());
        Map<Long, String> userMap = venueManageUserAccountService.listUserAccount(createBys);
        // 数据转换，封装创建人
        List<ViolationProjectVO> voList = list
                .stream()
                .map(violationProject -> {
                    ViolationProjectVO violationProjectVO = BeanUtil.toBean(violationProject, ViolationProjectVO.class);
                    String createByName = userMap.get(violationProject.getCreatedBy());
                    violationProjectVO.setCreatedByName(createByName);
                    return violationProjectVO;
                })
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public Page<ViolationProjectVO> listForVenue(PageParams<ViolationProjectDTO> pageParams) {
        log.info("listForVenue - 场馆查询违规项目, pageParams={}", pageParams);
        return listViolationProjectVO(pageParams, this::createViolationProjectQueryWrapper);
    }

    @Override
    public Page<ViolationProjectVO> listForHome(PageParams<ViolationProjectDTO> pageParams) {
        log.info("listForHome - 主场查询违规项目, pageParams={}", pageParams);
        return listViolationProjectVO(pageParams, this::createViolationProjectQueryWrapperForHome);
    }

    @Override
    public ViolationProjectVO getVOById(Long id) {
        log.info("getVOById - id获取违规项目, id={}", id);
        ViolationProject violationProject = getById(id);
        if (violationProject == null) {
            return null;
        }
        ViolationProjectVO violationProjectVO = BeanUtil.toBean(violationProject, ViolationProjectVO.class);
        UserAccountVo userAccountVO = venueManageUserAccountService.findSimpleById(violationProject.getCreatedBy());
        if (userAccountVO != null) {
            violationProjectVO.setCreatedByName(userAccountVO.getRealName());
        }
        return violationProjectVO;
    }

    private QueryWrapper<ViolationProject> createViolationProjectQueryWrapper(ViolationProjectDTO query) {
        QueryWrapper<ViolationProject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ViolationProject::getIsDeleted, BusinessConstant.DELETE_NO)
                .like(StrUtil.isNotBlank(query.getViolationContent()), ViolationProject::getViolationContent, query.getViolationContent())
                .between(StrUtil.isNotBlank(query.getStartCreateTime()) && StrUtil.isNotBlank(query.getEndCreateTime()),
                        ViolationProject::getCreateTime, query.getStartCreateTime(), query.getEndCreateTime())
                .eq(StrUtil.isNotBlank(query.getBelongSystem()), ViolationProject::getBelongSystem, query.getBelongSystem())
                .in(query.getBelongSystemList() != null && !query.getBelongSystemList().isEmpty(), ViolationProject::getBelongSystem, query.getBelongSystemList())
        ;
        return queryWrapper;
    }

    private QueryWrapper<ViolationProject> createViolationProjectQueryWrapperForHome(ViolationProjectDTO query) {
        QueryWrapper<ViolationProject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ViolationProject::getIsDeleted, BusinessConstant.DELETE_NO)
                .like(StrUtil.isNotBlank(query.getViolationContent()), ViolationProject::getViolationContent, query.getViolationContent())
                .between(StrUtil.isNotBlank(query.getStartCreateTime()) && StrUtil.isNotBlank(query.getEndCreateTime()),
                        ViolationProject::getCreateTime, query.getStartCreateTime(), query.getEndCreateTime())
                .eq(StrUtil.isNotBlank(query.getBelongSystem()), ViolationProject::getBelongSystem, query.getBelongSystem())
                .in(query.getBelongSystemList() != null && !query.getBelongSystemList().isEmpty(), ViolationProject::getBelongSystem, query.getBelongSystemList())
                .and(isHomeQueryWrapper -> isHomeQueryWrapper
                        .eq(query.getExhibitionManageId() != null, ViolationProject::getExhibitionManageId, query.getExhibitionManageId())
                        .eq(query.getHomeId() != null, ViolationProject::getHomeId, query.getHomeId())
                        .eq(ViolationProject::getBelongSystem, MenuAffiliationEnum.P_COMPOSITE_COURT.getCode())
                        .or()
                        .eq(ViolationProject::getBelongSystem, MenuAffiliationEnum.P_COMPOSITE_VENUE.getCode())
                )
        ;
        return queryWrapper;
    }
}
